<?php

namespace app\home\logic;

use  app\home\logic\SignUtil;
use think\File;
use think\Model;

class Fuyh5 extends Model
{

    public $rsa_key, $rsa_pub_key, $mchntcd, $backurl, $homeurl, $reurl, $post_url, $type, $cash_url, $cash_homeurl, $ver;

    protected function initialize()
    {
        parent::initialize();
        $this->type = 1;//0线下支付1线上支付
        $this->ver = '0.44';

        //正式
        $this->mchntcd = config('pay.mchnt_cd');
        $this->rsa_key = config('pay.rsa_key');
        $this->rsa_pub_key = config('pay.rsa_pub_key');
        $this->post_url = config('pay.url');
        //提现
        $this->cash_url = url('withdraw/notify', 'payment=fuyh5', true, true); //异回调
        $this->cash_homeurl = url('withdraw/homeurl', 'payment=fuyh5', true, true); //同步回调
        //充值
        $this->backurl = url('charge/notify', 'payment=fuyh5', true, true);
        $this->homeurl = url('charge/homeurl', 'payment=fuyh5', true, true);
        $this->reurl = url('charge/reurl', 'payment=fuyh5', true, true);
    }

    //充值
    public function submit($data = [])
    {
        $url = $this->post_url . 'app/500002.action';

        if (!isset($data['money']) || !is_numeric($data['money']) || $data['money'] <= 0) {
            return ['code' => 0, 'msg' => '金额有误!'];
        }


        $mchnt_cd = $this->mchntcd;

        $mchnt_txn_ssn = $data['order_id'];
        $amt = $data['money'] * 100;
        $back_notify_url = $this->backurl;
        $login_id = $data['login_id'];
        $page_notify_url = $this->homeurl;


        $dataArr = [
            $amt,
            $back_notify_url,
            $login_id,
            $mchnt_cd,
            $mchnt_txn_ssn,
            $page_notify_url,
        ];
        $dataStr = implode('|', $dataArr);
        $rsaKey = $this->rsa_key;
        $signature = SignUtil::sign($dataStr, $rsaKey);
        $queryData = [
            'amt' => $amt,
            'mchnt_cd' => $mchnt_cd,
            'login_id' => $login_id,
            'back_notify_url' => $back_notify_url,
            'page_notify_url' => $page_notify_url,
            'mchnt_txn_ssn' => $mchnt_txn_ssn,
            'signature' => $signature,
        ];

        $formStr = '';
        foreach ($queryData as $k => $v) {
            $formStr .= "<input type='hidden' name='{$k}' value='{$v}' />";
        }

        $cont = "
        <form id='form1' name='form1' method='post' action='{$url}'>
        " . $formStr . "
        </form>";
        $this->LogWirte('充值REQUEST' . PHP_EOL .var_export($queryData, true));
        return ['code' => 1, 'msg' => $cont ,'order_id' => $mchnt_txn_ssn];
    }

    //提现
    public function cash($data = [])
    {
        $url = $this->post_url . 'app/500003.action';
        if (!isset($data['amt']) || !is_numeric($data['amt']) || $data['amt'] <= 0) {
            return ['code' => 0, 'msg' => '金额有误!'];
        }

        $mchnt_cd = $this->mchntcd;

        $mchnt_txn_ssn = $data['mchnt_txn_ssn'];
        $amt = $data['amt'] * 100;
        $back_notify_url = $this->cash_url;
        $login_id = $data['login_id'];
        $page_notify_url = $this->cash_homeurl;


        $dataArr = [
            $amt,
            $back_notify_url,
            $login_id,
            $mchnt_cd,
            $mchnt_txn_ssn,
            $page_notify_url,
        ];
        $dataStr = implode('|', $dataArr);
        $rsaKey = $this->rsa_key;
        $signature = SignUtil::sign($dataStr, $rsaKey);
        $queryData = [
            'amt' => $amt,
            'mchnt_cd' => $mchnt_cd,
            'login_id' => $login_id,
            'back_notify_url' => $back_notify_url,
            'page_notify_url' => $page_notify_url,
            'mchnt_txn_ssn' => $mchnt_txn_ssn,
            'signature' => $signature,
        ];

        $formStr = '';
        foreach ($queryData as $k => $v) {
            $formStr .= "<input type='hidden' name='{$k}' value='{$v}' />";
        }

        $cont = "
        <form id='form1' name='form1' method='post' action='{$url}'>
        " . $formStr . "
        </form>";
        $this->LogWirte('提现REQUEST' . PHP_EOL .var_export($queryData, true));
        return ['code' => 1, 'msg' => $cont, 'order_id' => $mchnt_txn_ssn];
    }

    //
    /**
     * 注册开户
     * @param array $data
     * @return mixed
     *
     */
    public function regAction($data = [])
    {
        $url = $this->post_url .'reg.action';
        $password = '';
        $lpassword = '';
        $mchnt_cd = $this->mchntcd;
        $capAcntNm = '';
        $bank_nm = '';
        $email = '';
        $rem = '';
        $ver = '0.44';
        extract($data);
        $parent_bank_id = $this->getBankCode($bank);
        $dataArr = [
            $bank_nm,
            $capAcntNm,
            $capAcntNo,
            $certif_id,
            $city_id,
            $cust_nm,
            $email,
            $lpassword,
            $mchnt_cd,
            $mchnt_txn_ssn,
            $mobile_no,
            $parent_bank_id,
            $password,
            $rem,
            $ver,
        ];


        $dataStr = implode('|', $dataArr);

        $rsaKey = $this->rsa_key;
        $signature = SignUtil::sign($dataStr, $rsaKey);
        $queryData = [
            'bank_nm' => $bank_nm,
            'capAcntNm' => $capAcntNm,
            'capAcntNo' => $capAcntNo,
            'certif_id' => $certif_id,
            'certif_type' => '0',
            'city_id' => $city_id,
            'cust_nm' => $cust_nm,
            'email' => $email,
            'lpassword' => $lpassword,
            'mchnt_cd' => $mchnt_cd,
            'mchnt_txn_ssn' => $mchnt_txn_ssn,
            'mobile_no' => $mobile_no,
            'parent_bank_id' => $parent_bank_id,
            'password' => $password,
            'rem' => $rem,
            'ver' => $ver,
            'signature' => $signature,
        ];
        $queryData = http_build_query($queryData);
        $content = $this->postData($url, $queryData);
        $obj = json_decode(json_encode(simplexml_load_string($content)), true);
        $this->LogWirte('注册REQUEST' . PHP_EOL .var_export($queryData,true));
        $this->LogWirte('注册RESPONSE'. PHP_EOL .var_export($obj, true));
        return $obj;
    }

    public function test($data = [])
    {
        if (!isset($data['money']) || !is_numeric($data['money']) || $data['money'] <= 0) {
            return ['code' => 0, 'msg' => '金额有误!'];
        }
        if (!isset($data['user_bank'])) {
            return ['code' => 0, 'msg' => '银行卡信息有误!'];
        }
        $user = $data['user_bank'];
        $mchntcd = $this->mchntcd;
        $key = $this->rsa_key;
        $post_url = $this->post_url;

        $type = 10;
        $version = '2.0';
        $mchntorderid = $user['user_id'] . time() . rand(1000, 9999);
        $userid = $user['user_id'];
        $amt = $data['money'] * 100;
        $bankcard = $user['account'];
        $backurl = $this->backurl;
        $name = $user['name'];
        $idno = $user['id_card'];
        $idtype = '0';
        $logotp = '0';
        $homeurl = $this->homeurl;
        $reurl = $this->reurl;
        $signtp = 'md5';

        $recharge_data['money'] = $data['money'];
        $recharge_data['payment'] = 45;
        $recharge_data['user_id'] = $user['user_id'];
        $recharge_data['status'] = 0;
        $recharge_data['remark'] = "在线充值(fuyh5)";
        $recharge_data['nid'] = $mchntorderid;
        model('account_recharge')->add($recharge_data); //添加充值订单，返回ID号

        $sign = $type . "|" . $version . "|" . $mchntcd . "|" . $mchntorderid . "|" . $userid . "|" . $amt . "|" . $bankcard . "|" . $backurl . "|" . $name . "|" . $idno . "|" . $idtype . "|" . $logotp . "|" . $homeurl . "|" . $reurl . "|" . $key;
        $sign = str_replace(' ', '', $sign);
        //$this->log('1,' . date('Y-m-d H:i:s') . ':' . $sign . "\n");
        //$this->log('2,' . date('Y-m-d H:i:s') . ':' . md5($sign) . "\n");
        $fm = "<ORDER>"
            . "<VERSION>" . $version . "</VERSION>"
            . "<LOGOTP>" . $logotp . "</LOGOTP>"
            . "<MCHNTCD>" . $mchntcd . "</MCHNTCD> "
            . "<TYPE>" . $type . "</TYPE>"
            . "<MCHNTORDERID>" . $mchntorderid . "</MCHNTORDERID>"
            . "<USERID>" . $userid . "</USERID>"
            . "<AMT>" . $amt . "</AMT>"
            . "<BANKCARD>" . $bankcard . "</BANKCARD>"
            . "<NAME>" . $name . "</NAME>"
            . "<IDTYPE>" . $idtype . "</IDTYPE>"
            . "<IDNO>" . $idno . "</IDNO>"
            . "<BACKURL>" . $backurl . "</BACKURL>"
            . "<HOMEURL>" . $homeurl . "</HOMEURL>"
            . "<REURL>" . $reurl . "</REURL>"
            . "<REM1></REM1>"
            . "<REM2></REM2>"
            . "<REM3></REM3>"
            . "<SIGNTP>" . $signtp . "</SIGNTP>"
            . "<SIGN>" . md5($sign) . "</SIGN>"
            . "</ORDER>";

        $mstr = $this->des_ecb_encrypt($fm, $key);
        $mstr = str_replace(' ', '', $mstr);

        echo '<html>
        <head></head><body onload="document.form1.submit()">
        <form action="' . $post_url . '" method="post" name="form1" > 
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   加密标志：<input type="text" name="ENCTP" value="1" style="width:300px;">
   <br><br>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   版本号：<input type="text" name="VERSION" value="2.0" style="width:300px;">
   <br><br>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   商户代码：<input type="text" name="MCHNTCD" value="' . $mchntcd . '" style="width:300px;">
   <br><br>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   logo标志：<input type="text" name="LOGOTP" value="0" style="width:300px;">
   <br><br>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   订单信息：<input type="text" name="FM" value="' . $mstr . '" style="width:300px;">
   <br><br>
</form></body></html>
        ';
        exit;

        return $url;
    }

    public function callback($data = [])
    {
        $this->LogWirte('充值RESPONSE'. PHP_EOL .var_export($_POST, true));
        $mchntcd = $this->mchntcd;
        $respose_code = $data['resp_code'];
//        $respose_desc = $data['resp_desc'];
        $order_id = $data['mchnt_txn_ssn'];
        $amt = $data['amt'];
        $login_id = $data['login_id'];
        $signature = $data['signature'];

        $signStr = $amt . "|" . $login_id . "|" . $mchntcd . "|" . $order_id . "|" . $respose_code;
        $res = SignUtil::verify($signStr, $signature, $this->rsa_pub_key);
        if (empty($res)) {
            return '非法访问';
        }

        db()->startTrans();
        if ($respose_code == '0000') {
            $re = model('charge', 'logic')->OnlineReturn(['trade_no' => $order_id, 'sign' => $signature]);

        } else {
            $re = model('charge', 'logic')->OnlineReturnNo(['trade_no' => $order_id, 'verify_remark' => urldecode($data['resp_desc']), 'sign' => $signature]);
        }
        if ($re) {
            db()->commit();
            return true;
        } else {
            db()->rollback();
            return false;
        }
        exit;
    }

    /**
     * @param $data
     * 冻结
     * @return mixed
     */
    public function freezeAction($data = [])
    {
        $url = $this->post_url .'freeze.action';
        $rem = $data['rem'] ? $data['rem'] : '';
        $cust_no = $data['cust_no'];
        $amt = $data['amt'] * 100;
        $mchnt_txn_ssn = $data['mchnt_txn_ssn'];
        $dataArr = [
            $amt,
            $cust_no,
            $this->mchntcd,
            $mchnt_txn_ssn,
            $rem,
            $this->ver,
        ];
        $dataStr = implode('|', $dataArr);
        $rsaKey = $this->rsa_key;
        $signature = SignUtil::sign($dataStr, $rsaKey);
        $queryData = [
            'amt' => $amt,
            'cust_no' => $cust_no,
            'mchnt_cd' => $this->mchntcd,
            'mchnt_txn_ssn' => $mchnt_txn_ssn,
            'rem' => $rem,
            'ver' => $this->ver,
            'signature' => $signature,
        ];
//        return $queryData;

        $queryData = http_build_query($queryData);
        $content = $this->postData($url, $queryData);
        $obj = simplexml_load_string($content);
        $this->LogWirte('冻结REQUEST' . PHP_EOL .var_export($queryData,true) . $url);
        $this->LogWirte('冻结RESPONSE'. PHP_EOL .var_export($obj, true));
        return $obj;
    }

    /**
     * @param $bank
     * @return mixed
     */
    public function getBankCode($bank)
    {
        $arr = [
            'ICBC' => '0102',
            'CCB' => '0105',
            'CMBC' => '0305',
            'PSBC' => '0100',
            'CEB' => '0303',
            'HXBANK' => '0304',
            'CMB' => '0308',
            'BOC' => '0104',
            'SPDB' => '0310',
            'CIB' => '0309',
            'CITIC' => '0302',
            'BJBANK' => '04031000',
            'GDB' => '0306',
            'SPABANK' => '0307',
            'CZBANK' => '0316',
            'ABC' => '0103',
            'LYBANK' => '04184930',
            'COMM' => '0301',
        ];
        return $arr[$bank];
    }

    public function postData($url, $data)
    {
        $ch = curl_init();
        $timeout = 300;
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_REFERER, "http://localhost");   //站点
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $handles = curl_exec($ch);
        if ($handles == false) {
            $error = curl_error($ch);
            curl_close($ch);
            return $error;
        }
        curl_close($ch);
        return $handles;
    }
    //写日志
    public function LogWirte($Astring)
    {
        $path = config('log.path')."fuyoupay/";
        $file = $path.date('Ymd',time()).".txt";
        if(!is_dir($path)){	mkdir($path); }
        $LogTime = date('Y-m-d H:i:s',time());
        if(!file_exists($file))
        {
            $logfile = fopen($file, "w") or die("Unable to open file!");
            fwrite($logfile, "[$LogTime]:".$Astring."\r\n");
            fclose($logfile);
        }else{
            $logfile = fopen($file, "a") or die("Unable to open file!");
            fwrite($logfile, "[$LogTime]:".$Astring."\r\n");
            fclose($logfile);
        }
    }

}